﻿
using System;
using System.IO;
using System.Text;
using System.Xml.Serialization;
namespace HuaCheng.Controller
{
    public class XmlManager
    {
        //xml存储路径
        public static string NewDevCalibraPath = Environment.CurrentDirectory + "\\kb.xml";
        /// <summary>
        /// 序列化xml
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="filePath"></param>
        /// <param name="obj"></param>
        /// <param name="useGb2312"></param>
        public static void XmlSeria<T>(string filePath, T obj, bool useGb2312 = false)
        {
            try
            {
                var writer = !useGb2312 ? new StreamWriter(filePath) : new StreamWriter( filePath, false, Encoding.GetEncoding("gb2312"));
                XmlSerializer xs = new XmlSerializer(typeof(T));               
                XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                ns.Add("", "");
                xs.Serialize(writer,obj,ns);
                writer.Close();          
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + ex.StackTrace);
            }
        }
        /// <summary>
        /// 反序列化xml
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="filePath"></param>
        /// <param name="useGb2312"></param>
        /// <returns></returns>
        public static T XmlDeSeria<T>(string filePath,bool useGb2312=false)
        {
            if (!File.Exists(filePath))
            {
                return default(T);
            }
            try
            {
                var reader = !useGb2312 ? new StreamReader(filePath) : new StreamReader(filePath,Encoding.GetEncoding("gb2312"));
                XmlSerializer xs = new XmlSerializer(typeof(T));
                T ret = (T)xs.Deserialize(reader);
                reader.Close();
                return ret;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + ex.StackTrace);
                return default(T);
            }
        }
    }
}
